<?php
//this model is using for states....
class Area_model extends Model{
	
	function area_model()
	{
		parent::Model();
		$this->load->database();
	}
	
  //to get area names...
  public function get_areas( $id =0 ) 
  {
    $this->CI =& get_instance();
    //Select table name
        
    //Build contents query
//    $this->db->query()
    $this->db->select('* from tbl_area where city_id= '.$id );
    $this->CI->flexigrid->build_query();
    
    //Get contents
    $return['records'] = $this->db->get();
    
    //Build count query
    $this->db->select('count(area_id) as record_count from tbl_area where city_id='.$id );
    $this->CI->flexigrid->build_query(FALSE);
    $record_count = $this->db->get();
    $row = $record_count->row();
    
    //Get Record Count
    $return['record_count'] = $row->record_count;
  
    //Return all
    return $return;
  }
  //to get city name to display flexigrid...
  function get_cityname($id=0)
  {
    $result = $this->db->query("select * from tbl_city where city_id=".$id);
    return $result;
    
  }
  
  
	//to insert new city...
	function insert_area()
	{
	
		$check = $this->db->query("select * from tbl_area where city_id='".$_POST['cities']."' and area_name like '".$_POST['area_name']."'");
		
		if($check->num_rows() == 0)
		{
			$this->db->set('city_id', $_POST['cities']);
			$this->db->set('area_name', $_POST['area_name']);
      $this->db->set('area_pincode',$_POST['pincode']);
			$this->db->insert('tbl_area');	
		}
		else
		{
			redirect("areas/duplicate_area");
		}
		
	}
	
	function insert_areas_bulk($files='')
	{
		require_once 'excel_reader2.php';
        $xls = new Spreadsheet_Excel_Reader('./areas_uploads/'.$files);
    
    
    $areas = $xls->dump_areas();
	
	foreach($areas as $area)
	{
		$area_name= preg_replace('/[^\w\d_ -]/si', '', $area['areas']);
			
		$check = $this->db->query("select * from tbl_area where area_name like '".$area_name."' AND area_pincode='".$area['pincode']."' AND city_id='".$_POST['cities']."'");
		
		if($check->num_rows() == 0)
		{
			$this->db->set('area_name',$area_name);
			$this->db->set('area_pincode',$area['pincode']);
			$this->db->set('city_id',$_POST['cities']);
			$this->db->insert('tbl_area');	
		} 
	}
	  
	
    	
	}
	
	//to display areas...
	function disp_areas($id=0)
	{
		
		$name = $this->db->query("select * from tbl_area where city_id='".$id."' order by area_name ASC ");
		return $name;
	}
	//to get display pincode
	function disp_pincode($id=0)
	{
		$pincode = $this->db->query("select * from tbl_area where area_id=".$id);
		return $pincode;
	}
	
	function area_edit($id)
	{
		$result = $this->db->query("select * from tbl_area where area_id =".$id);
		return $result;
	}
	
	//to save edited city name
	function save_edit()
	{
		//print_r($_POST);
		$data = array(
               'area_name' => $_POST['area_name'],
            );
            
                $this->db->where('area_id', $_POST['id']);
		$this->db->update('tbl_area', $data); 
	}
	
}
